package basic.thread.again;

/**
 * 线程等待唤醒
 *
 * @author bingo
 * @create 2018-03-02 9:51
 **/
public class Demo8 {

 public  static Demo8 demo8 = new Demo8();

    private  volatile Integer  value = 0;

    public  synchronized  void a(){
        System.out.println("a");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("a执行完毕");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public  synchronized  void b(){
        System.out.println("b");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("b执行完毕");
    }

    public synchronized Integer getValue() {
        System.out.println(Thread.currentThread().getName()+"开始执行");
        if(value!=6){
            try {
                demo8.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"执行完毕");
        return value;
    }

    public synchronized  void setValue(Integer value) {
        System.out.println(Thread.currentThread().getName()+"开始设置值");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.value = value;
        demo8.notifyAll();
        System.out.println(Thread.currentThread().getName()+"设置值完成");
    }

    public static void main(String[] args) {

       new Thread(new Runnable() {
            @Override
            public void run() {
                demo8.setValue(6);
            }
        }).start();



        new Thread(new Runnable() {
            @Override
            public void run() {
                demo8.getValue();
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                demo8.getValue();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                demo8.getValue();
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                demo8.getValue();
            }
        }).start();


      new Thread(new Runnable() {
          @Override
          public void run() {
              demo8.a();
          }
      }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                demo8.b();
            }
        }).start();
    }





}
